#include "ResourceLoader.h"
#include <QDir>
#include <QFile>
#include <iostream>
#include "CommonExceptions.h"
#include "ClassMetaManager.h"
#include "ResourceManager.h"



_NS_OOP_BEGIN



ResourceLoader::ResourceLoader ()
{
}



P_Object
ResourceLoader::loadObject (const QString& r_name)
{
	// return the object if loaded
	auto it_result = ResourceManager::ref ()._objects.find (r_name);
	if (it_result != ResourceManager::ref ()._objects.end ()) {
#ifdef OOPUTILS_DEBUG
		std::cout << "Object " << r_name.toStdString () << " already loaded" << std::endl;
#endif
		return it_result->first;
	}

	// load object from file
#ifdef OOPUTILS_DEBUG
	std::cout << "Load object " << r_name.toStdString () << std::endl;
#endif
	auto filePath = QDir (ResourceManager::ref ()._dir).filePath (r_name);
	QFile file (filePath);
	if (!file.open (QFile::ReadOnly))
		OOPTHROW (InvalidArgumentException (
				QString ("The file '%1' cannot be opened for read")
						.arg (filePath)));
	_inStream.setDevice (&file);
	QString className;
	_inStream >> className;
	auto p_obj = ClassMetaManager::ref ().getMeta (className).creator ();
	p_obj->_name = r_name;
	p_obj->read (*this);
	p_obj->_syncStatus = Object::NOT_CHANGED;
	ResourceManager::ref ()._recordLoadedObject (p_obj);
	return p_obj;
}



_NS_OOP_END